package com.tg.app.activity.device.add;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.text.HtmlCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.tange.module.add.ap.DefaultApMatchRule;
import com.tange.module.add.ap.DeviceApScanner;
import com.tange.module.core.wifi.scan.ApScanConfiguration;
import com.tg.app.R;
import com.tg.app.adapter.ApDeviceAdapter;
import com.tg.app.report.DeviceAddReport;
import com.tg.app.report.DeviceAddReportBean;
import com.tg.app.util.LogUtils;
import com.tange.base.toolkit.AppUtil;
import com.tg.appcommon.android.DeviceAddSoundConstants;
import com.tg.appcommon.android.SoundPlayerManager;
import com.tg.appcommon.android.TGLog;
import com.tange.base.toolkit.TGThreadPool;
import com.tg.appcommon.android.TGWifiUtil;
import com.tg.data.helper.DeviceTypeHelper;


import java.util.ArrayList;
import java.util.List;

public class ApDeviceListActivity extends ApBaseActivity implements  View.OnClickListener {
    public static final String TAG ="ApDeviceListActivity";
    private RecyclerView recyclerView;
    private ApDeviceAdapter apDeviceAdapter;
    private final List<ScanResult> wifiApList = new ArrayList<>();
    private ImageView imageView;

    private boolean playSound = true;

    private SoundPlayerManager soundPlayerManager;

    private final Handler uiHandler = new Handler(Looper.getMainLooper());

    private DeviceApScanner deviceApScanner;

    private void goToWifiSetting(String wifi) {
        Intent intent = new Intent(getBaseContext(), ApSetWifiActivity.class);
        intent.putExtra(ApSetWifiActivity.EXT_UUID, wifi);
        intent.putExtra(ApSetWifiActivity.EXT_DEVICE_TYPE, getIntent().getStringExtra(ApSetWifiActivity.EXT_DEVICE_TYPE));
        startActivityForResult(intent,0);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        String deviceType = getIntent().getStringExtra(ApSetWifiActivity.EXT_DEVICE_TYPE);
        if (DeviceTypeHelper.isLockBell(deviceType)) {
            playSound = false;
        }

        deviceApScanner = DeviceApScanner.create(this, new DefaultApMatchRule(ApScanConfiguration.INSTANCE.apNamePrefix()), new DeviceApScanner.Callback() {
            @Override
            public void onDeviceApRefresh(List<ScanResult> apList) {
                if (apList == null) return;

                TGLog.i(TAG, "[DeviceApScanner] onDeviceApRefresh: " + apList);

                wifiApList.clear();
                wifiApList.addAll(apList);


                if (wifiApList.size()>0){
                    recyclerView.setVisibility(View.VISIBLE);
                    imageView.setVisibility(View.GONE);
                }else  {
                    recyclerView.setVisibility(View.GONE);
                    imageView.setVisibility(View.VISIBLE);
                }
                apDeviceAdapter.notifyDataSetChanged();
            }

            @Override
            public void onWiFiRefresh(List<ScanResult> wifiList) {

            }

            @Override
            public void onError(int errorCode) {
                TGLog.i(TAG, "[DeviceApScanner] onError: " + errorCode);
                if (errorCode == DeviceApScanner.ERROR_DEVICE_AP_NOT_FOUND) {
                    hideLoading();
                    deviceNoFound();
                }
            }

            @Override
            public void onFinish() {
                TGLog.i(TAG, "[onFinish] ");
            }
        });


        setContentView(R.layout.fragment_ap_device_list);
        hideActionBar();
        initView();
    }

    @Override
    public boolean shouldSetStatusBarColor() {
        return true;
    }

    @Override
    public void onResume() {
        super.onResume();
        wifiConnected();
        deviceApScanner.startScan();
        playSound();
    }

    private void playSound() {
        if (!playSound) return;
        if (soundPlayerManager != null) {
            soundPlayerManager.destroy();
        }
        soundPlayerManager = SoundPlayerManager.create(this);
        uiHandler.postDelayed(() -> {
            if (soundPlayerManager != null) {
                soundPlayerManager.download(DeviceAddSoundConstants.WifiList(ApDeviceListActivity.this), true);
            }
        }, 1000);
    }

    @Override
    public void onPause() {
        super.onPause();
        pauseSound();
        deviceApScanner.stopScan();
    }

    private void pauseSound() {
        if (!playSound) return;
        uiHandler.removeCallbacksAndMessages(null);
        if (soundPlayerManager != null) {
            soundPlayerManager.destroy();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void initView() {
        recyclerView = findViewById(R.id.device_add_ap_camera_list);
        findViewById(R.id.add_device_research).setOnClickListener(this);
        findViewById(R.id.tv_add_device_no_found).setOnClickListener(this);
        imageView =findViewById(R.id.icon_device_ap_add_search);
        LinearLayoutManager linearLayoutManager =   new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        apDeviceAdapter = new ApDeviceAdapter(wifiApList, position -> {
            LogUtils.trackCustomBeginKVEvent(this,"bind_ap_new","connect_get_wifi");
            if (wifiApList.size()>position){
                ScanResult ap = wifiApList.get(position);

                // 判断设备热点是否有密码，有密码直接跳到 设备热点密码设置页面 ，无密码则直接去原有WIFI设置页面
                if (TGWifiUtil.isWiFiSecurity(ap)) {
                    String selectedWifiName = ap.SSID.replace("\"","");
                    // 如果当前WIFI已经是目标WIFI，那不用设置密码了，直接去WIFI设置页面
                    goToWifiSetting(ap.SSID);
                } else {
                    goToWifiSetting(ap.SSID);
                }
            }

        });
        recyclerView.setAdapter(apDeviceAdapter);
        //Glide.with(this).asGif().load(R.mipmap.search_ok).into(imageView);
        findViewById(R.id.back_toolbar).setOnClickListener(v -> finish());
        TGThreadPool.executeOnUiThreadDelayed(this::tipsDialog, 500);
    }


    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public void wifiListChanged() {
    }

    @Override
    public void wifiConnected() {

    }

    @Override
    protected void wifiUnavailable() {
        hideLoading();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_add_device_no_found) {
            deviceNoFound();
        }
    }

    private void deviceNoFound(){
        deviceApScanner.stopScan();
        @SuppressLint("InflateParams") View view = LayoutInflater.from(this).inflate(R.layout.dialog_search_device_settings, null);
        TextView title = view.findViewById(R.id.deivce_settings_title_mark);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            title.setText(Html.fromHtml(String.format(getResources().getString(R.string.deivce_settings_title_mark), ApScanConfiguration.INSTANCE.apNamePrefix())));
        } else {
            title.setText(HtmlCompat.fromHtml(String.format(getResources().getString(R.string.deivce_settings_title_mark), ApScanConfiguration.INSTANCE.apNamePrefix()), HtmlCompat.FROM_HTML_MODE_LEGACY));
        }
        mDialog = new Dialog(this, com.module.appcommon.R.style.alert_dialog);
        mDialog.setContentView(view);
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.show();
        view.findViewById(R.id.btn_dialog_search_settings_cancel).setOnClickListener(v -> {
            dismissDialog();
            deviceApScanner.restartScan();
        });
        view.findViewById(R.id.btn_dialog_search_settings_submit).setOnClickListener(v -> {
            dismissDialog();
            startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
            DeviceAddReportBean bean = DeviceAddReport.getInstance().getReportBean();
            if (bean!=null){
                bean.isConfingWifi = 1;
            }
        });
    }
    private Dialog mDialog = null;
    private void tipsDialog(){
        if (!AppUtil.isActivityFinishingOrDestroyed(ApDeviceListActivity.this)){
            @SuppressLint("InflateParams") View view = LayoutInflater.from(this).inflate(R.layout.dialog_search_device, null);
            mDialog = new Dialog(this, com.module.appcommon.R.style.alert_dialog);
            mDialog.setContentView(view);
            mDialog.setCanceledOnTouchOutside(false);
            mDialog.show();
            view.findViewById(R.id.btn_dialog_search_device).setOnClickListener(v -> dismissDialog());
        }
    }

    private void dismissDialog() {
        if (mDialog != null && mDialog.isShowing()){
            mDialog.dismiss();
            mDialog = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dismissDialog();
    }
}
